package com.zm.xiaohashu.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.zm.xiaohashu.gateway.constant.RedisKeyConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取权限列表
     *
     * @param loginId
     * @param loginType
     * @return
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的权限列表
        log.info("## 获取用户权限列表, loginId: {}", loginId);
        Long userId = Long.valueOf(loginId.toString());
        String userRoleKey = RedisKeyConstants.buildUserRoleKey(userId);
        String roleListJson = redisTemplate.opsForValue().get(userRoleKey);
        List<String> roleKeyList = JSONUtil.toList(roleListJson, String.class);// 获取角色列表
        if (CollUtil.isEmpty(roleKeyList)) {
            return Collections.emptyList();
        }
        List<String> permissionList = new ArrayList<>();// 创建权限列表
        for (String roleKey : roleKeyList) {
            String rolePermissionsKey = RedisKeyConstants.buildRolePermissionsKey(roleKey);
            String rolePermissionsJson = redisTemplate.opsForValue().get(rolePermissionsKey);
            List<String> rolePermissions = JSONUtil.toList(rolePermissionsJson, String.class);
            permissionList.addAll(rolePermissions);
        }
        if (CollUtil.isEmpty(permissionList)) {
            return Collections.emptyList();
        }
        return permissionList;
    }

    /**
     * 获取角色列表
     *
     * @param loginId
     * @param loginType
     * @return
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的角色列表
        log.info("## 获取用户角色列表, loginId: {}", loginId);
        String roleListKey = RedisKeyConstants.buildUserRoleKey(Long.parseLong(loginId.toString()));
        Object roleListJson = redisTemplate.opsForValue().get(roleListKey);
        if (Objects.isNull(roleListJson)) {
            return Collections.emptyList();
        }
        List<String> roleList = JSONUtil.toList(roleListJson.toString(), String.class);
        if (CollUtil.isEmpty(roleList)) {
            return Collections.emptyList();
        }
        return roleList;
    }

}